package com.kun.springsecurity.handler;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author zhoukun
 * @Date 2021/2/15 21:30
 * 权限不足处理
 */
@Component
public class MyAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
            httpServletResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);
            // 设置响应头
            httpServletResponse.setHeader("Content-Type", "application/json;charset=utf-8");
            PrintWriter printWriter = httpServletResponse.getWriter();
            // 向页面中写内容
            printWriter.write("{\"status\":\"error\",\"msg\":\"权限不足，请联系管理员！\"}");
            printWriter.flush();
            printWriter.close();
    }
}
